package cn.zeal4j.filter;

import cn.zeal4j.util.HibernateUtil;
import org.hibernate.Transaction;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author Administrator
 * @file Hibernate-Tutorial
 * @create 2020 09 27 8:55
 */

@WebFilter("/*")
public class OpenSessionInViewFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Transaction transaction = null;
        try {
            transaction = HibernateUtil.getCurrentSession().beginTransaction();
            filterChain.doFilter(servletRequest, servletResponse);
            transaction.commit();
        } catch (Exception exception) {
            exception.printStackTrace();
            if (transaction != null) transaction.rollback();
        }
    }
}
